<!-- src/views/CreatePostView.vue -->
<template>
  <div class="create-post-container">
    <el-page-header @back="$router.go(-1)" content="发布新帖子" style="margin-bottom: 20px;" />

    <el-card class="create-post-card">
      <el-form
        ref="postFormRef"
        :model="postForm"
        :rules="postRules"
        label-width="80px"
        @submit.prevent="submitPost"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="postForm.title"
            placeholder="请输入帖子标题"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="板块" prop="categoryId">
          <el-select v-model="postForm.categoryId" placeholder="请选择板块" style="width: 100%;">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <!-- 可以根据需要替换为富文本编辑器，如 WangEditor, Quill.js -->
          <el-input
            v-model="postForm.content"
            type="textarea"
            :rows="15"
            placeholder="请输入帖子内容..."
            maxlength="65535"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitPost" :loading="loading">发布帖子</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { createPost } from '@/services/postService';
import { getCategories } from '@/services/categoryService'; // 需要创建 categoryService
import { ElMessage } from 'element-plus';

const router = useRouter();
const authStore = useAuthStore();

const postFormRef = ref();
const loading = ref(false);

const categories = ref([]); // 存储板块列表

const postForm = reactive({
  title: '',
  content: '',
  categoryId: null
});

const postRules = {
  title: [
    { required: true, message: '请输入帖子标题', trigger: 'blur' },
    { min: 1, max: 255, message: '标题长度为 1 到 255 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择板块', trigger: 'change' } // 注意是 change
  ],
  content: [
    { required: true, message: '请输入帖子内容', trigger: 'blur' },
    { min: 1, max: 65535, message: '内容长度不能超过 65535 个字符', trigger: 'blur' }
  ]
};

// 获取板块列表
const fetchCategories = async () => {
  try {
    // 假设后端有获取所有板块的 API
    const response = await getCategories(); // 需要实现 getCategories
    categories.value = response.data || [];
  } catch (error) {
    console.error('Failed to fetch categories:', error);
    ElMessage.error('获取板块列表失败');
  }
};

// 提交帖子
const submitPost = async () => {
  if (!postFormRef.value) return;
  await postFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const response = await createPost({
          title: postForm.title,
          content: postForm.content,
          categoryId: postForm.categoryId
        });
        console.log('Post created:', response.data);
        ElMessage.success('帖子发布成功！');
        // 跳转到新发布的帖子详情页
        router.push(`/posts/${response.data.id}`);
      } catch (error) {
        console.error('Post creation failed:', error);
        ElMessage.error(error.response?.data?.message || '发布失败');
      } finally {
        loading.value = false;
      }
    } else {
      console.log('Post form validation failed!');
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  postForm.title = '';
  postForm.content = '';
  postForm.categoryId = null;
};

// 组件挂载时获取板块列表
onMounted(() => {
  fetchCategories();
});
</script>

<style scoped>
.create-post-container {
  padding: 20px;
  max-width: 1000px; /* 限制最大宽度 */
  margin: 0 auto;
}
.create-post-card {
  /* 可以添加卡片样式 */
}
</style>
